import random
import time
from secrets import SECRET_TENCENT_SECRET_ID, SECRET_TENCENT_SECRET_KEY
from config import Constants
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tbp.v20190627 import tbp_client
from tencentcloud.tbp.v20190627 import models as tbp_models
import json
from utils_new.logger import logger

class AiAPI:
    def __init__(self, endpoint: str):
        super(AiAPI, self).__init__()
        self.cred = credential.Credential(SECRET_TENCENT_SECRET_ID, SECRET_TENCENT_SECRET_KEY)
        self.httpProfile = HttpProfile()
        self.httpProfile.endpoint = endpoint

        self.clientProfile = ClientProfile()
        self.clientProfile.httpProfile = self.httpProfile

    @staticmethod
    def generate_id() -> str:
        return str(random.randint(1, 2000))


class AiTbpAPI(AiAPI):
    g_terminal_id: int = None
    g_generate_time: float = None
    def __init__(self):
        super(AiTbpAPI, self).__init__("tbp.tencentcloudapi.com")
        self.client = tbp_client.TbpClient(self.cred, "", self.clientProfile)

    def start_new(self, terminal_id: int = None):
        try:
            req = tbp_models.TextResetRequest()
            if terminal_id is None:
                terminal_id = AiTbpAPI.generate_id()
            params = {
                "BotId": Constants.AI_BOT_ID,
                "BotEnv": Constants.AI_BOT_ENV,
                "TerminalId": terminal_id
            }
            req.from_json_string(json.dumps(params))

            resp = self.client.TextReset(req)
            logger.debug(f"{resp.to_json_string()}")
            resp_js = json.loads(resp.to_json_string())
            self.g_terminal_id = terminal_id
            self.g_generate_time = time.time()
            return terminal_id

        except Exception as err:
            logger.error(f'{err.__class__.__name__}: {err}')
            return None

    def chat(self, text, terminal_id: int = None) -> str:
        if terminal_id is None:
            if self.g_generate_time is None or \
                    (self.g_generate_time is not None and time.time() - self.g_generate_time > Constants.AI_BOT_TBP_MAX_SPACING):
                terminal_id = self.start_new()
            else:
                terminal_id = self.g_terminal_id
        if terminal_id is None:
            terminal_id = self.start_new()
        try:
            req = tbp_models.TextProcessRequest()
            params = {
                "BotId": Constants.AI_BOT_ID,
                "BotEnv": Constants.AI_BOT_ENV,
                "TerminalId": str(terminal_id),
                "InputText": text
            }
            req.from_json_string(json.dumps(params))

            resp = self.client.TextProcess(req)
            logger.debug(f"{resp.to_json_string()}")
            resp_js = json.loads(resp.to_json_string())
            text_all = ''
            for content_item in resp_js['ResponseMessage']['GroupList']:
                text_all += content_item.get('Content', '')
            return text_all

        except Exception as err:
            logger.error(f'{err.__class__.__name__}: {err}')
            return None

tbp_bot = AiTbpAPI()
